/*
 * @(#)TestSearch.java 1.0 05/04/10
 *
 * You can modify the template of this file in the
 * directory ..\JCreator\Templates\Template_1\Project_Name.java
 *
 * You can also create your own project template by making a new
 * folder in the directory ..\JCreator\Template\. Use the other
 * templates as examples.
 *
 */
package com.joe.common.tool;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;

class BibRecs
{
	public long [] recs;
	BibRecs()
	{
		recs = new long[0];
	}
}

public class libHoldings
{
	private static HashMap 	hash = new HashMap();
	
	//@SuppressWarnings("unchecked")
	public void load(Connection con , String[] libs)
		throws Exception
	{
		for(int i = 0 ; i < libs.length ; i++ )
		{
			String s = libs[i];
			BibRecs brs= new BibRecs();
			brs.recs= getLibHoldings(con,s);
			
			hash.put(s,brs);
		}
	}
	
	public long[] getLibHoldings(Connection con,String lib)
		throws Exception
	{
		Statement s = null;
		ResultSet res = null;

		s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        String sql = "SELECT distinct bookrecno FROM holding WHERE orglib = '";
        sql += lib;
        sql += "' ORDER BY bookrecno";
        res = s.executeQuery(sql);
		int ResultCounts = 0;
		if(res.last())
		{
			ResultCounts = res.getRow();
		}
		
		long[] recnos = new long[ResultCounts];
		
		if(ResultCounts==0)
			return new long[0];
			
		res.first();
		int count = 0;
		do
		{
			long bookrecno= res.getLong("bookrecno");

			recnos[count] = bookrecno;
				
			count++;
		}while(res.next());
		
		res.close();
		s.close();
		
		return recnos;
	}
	
	public long[] getLibRecs(String lib)
	{
		BibRecs brs = (BibRecs)hash.get(lib);
		
		return brs.recs;
	}
	
	public void dump()
	{
		Set keys = hash.keySet();
		Object[] s = keys.toArray();
		
		for(int i = 0;i < s.length; i++)
		{
			BibRecs brs = (BibRecs)hash.get((String)s[i]);
			
			System.out.print("libcode : " + s[i]);
			System.out.println(" has " + brs.recs.length + " items.");
		}
	}
	
	public String[] getLibcodes(long recno)
	{
		Set keys = hash.keySet();
		Object[] s = keys.toArray();

		String slib = "";		
		for(int i = 0;i < s.length; i++)
		{
			BibRecs brs = (BibRecs)hash.get((String)s[i]);
			
			if(Arrays.binarySearch(brs.recs,recno) >= 0 )
			{
				slib += (String)s[i];
				slib += ";";
			}
		}
		slib = slib.toLowerCase();
		return slib.split(";");
	}
	
	public static void main(String args[]) 
		throws Exception
	{

	}
}
